package com.wpp.register.config;

import com.wpp.constant.Constant;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Classname ZkConfigCenter
 * @Description TODO
 * @Date 2020/12/12 22:47
 * @Created by wpp25
 */
public class ZkConfigCenter implements ConfigCenter{

    private final CuratorFramework curatorFramework;

    public CuratorFramework getCuratorFramework() {
        return curatorFramework;
    }

    public ZkConfigCenter() {
        this.curatorFramework = CuratorFrameworkFactory.builder()
                .retryPolicy(new ExponentialBackoffRetry(1000,3))
                .connectString(Constant.ZkConfig.IP_LOCALHOST)
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .build();
        // 启动
        this.curatorFramework.start();
    }


    @Override
    public Properties loadConfig() {
        Properties properties = new Properties();
        String configRoot = Constant.ZkConfig.CONFIG_ROOT;

        initDataSourceConfigIfNecessary();

        try {
            List<String> configKeyPaths = curatorFramework.getChildren().forPath(configRoot);
            for (String configKeyPath : configKeyPaths) {
                byte[] configValueByte = curatorFramework.getData().forPath(configRoot + Constant.ZkConfig.SPILT + configKeyPath);
                properties.setProperty(configKeyPath,new String(configValueByte));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }


    @Override
    public void initDataSourceConfigIfNecessary() {

        for (Map.Entry<String, String> databaseEntity : Constant.DataSource.DATASOURCE_MAP.entrySet()) {
            String configKeyPath = Constant.ZkConfig.CONFIG_ROOT + Constant.ZkConfig.SPILT + databaseEntity.getKey();
            try {
                if (curatorFramework.checkExists().forPath(configKeyPath) != null) {
                    break;
                }
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(configKeyPath,databaseEntity.getValue().getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
